import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { getFootprintList, recordFootprint, deleteFootprint } from '@/api/modules/user'
import type { FootprintGoods } from '@/types/footprint'
import { useUserStore } from './user'

export const useFootprintStore = defineStore('footprint', () => {
  const footprintItems = ref<FootprintGoods[]>([])
  const isLoading = ref(false)
  const error = ref<string | null>(null)
  const total = ref(0)
  const userStore = useUserStore()

  // 获取足迹总数
  const footprintCount = computed(() => total.value)

  // 获取足迹列表（分页）
  async function fetchFootprintList(page = 1, size = 10) {
    // 检查是否有 token
    if (!userStore.token) {
      footprintItems.value = []
      return { list: [], pagination: { total: 0 } }
    }

    try {
      isLoading.value = true
      error.value = null
      const response:any = await getFootprintList({ page, size })
      if (response.code === 1000) {
        // 处理返回的数据，添加 typeName 字段
        const processedList = response.data.list.map((item: any) => ({
          ...item,
          typeName: item.gCategory // 使用商品分类作为类型名称
        }))

        if (page === 1) {
          footprintItems.value = processedList
        } else {
          footprintItems.value = [...footprintItems.value, ...processedList]
        }
        total.value = response.data.pagination.total
        return response.data
      } else {
        error.value = response.message || '获取足迹列表失败'
        return { list: [], pagination: { total: 0 } }
      }
    } catch (err) {
      error.value = '获取足迹列表失败'
      console.error('获取足迹列表失败:', err)
      return { list: [], pagination: { total: 0 } }
    } finally {
      isLoading.value = false
    }
  }

  // 添加足迹
  async function addToFootprint(goodsId: number) {
    if (!userStore.token) return false

    try {
      const response:any = await recordFootprint(goodsId)
      if (response.code === 1000) {
        await fetchFootprintList() // 重新获取足迹列表
        return true
      }
      return false
    } catch (err) {
      console.error('添加足迹失败:', err)
      return false
    }
  }

  // 删除足迹
  async function removeFromFootprint(id: number) {
    if (!userStore.token) return false

    try {
      const response:any = await deleteFootprint(id)
      if (response.code === 1000) {
        // 从本地列表中移除
        footprintItems.value = footprintItems.value.filter(item => item.id !== id)
        return true
      }
      return false
    } catch (err) {
      console.error('删除足迹失败:', err)
      return false
    }
  }

  // 清空足迹
  async function clearFootprints() {
    if (!userStore.token) return false

    try {
      // 遍历删除所有足迹
      await Promise.all(footprintItems.value.map(item => removeFromFootprint(item.id)))
      footprintItems.value = []
      return true
    } catch (err) {
      console.error('清空足迹失败:', err)
      return false
    }
  }

  return {
    footprintItems,
    isLoading,
    error,
    footprintCount,
    total,
    fetchFootprintList,
    addToFootprint,
    removeFromFootprint,
    clearFootprints
  }
}, {
  persist: true
}) 